<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { userRegisterService, sendEmailCodeService, getCheckCodeService } from '@/api/user.js'
import { ElMessage } from 'element-plus'
import { User, Lock, Message, Key } from '@element-plus/icons-vue'

const router = useRouter()

const formData = reactive({
    email: '',
    adminCode: '',
    emailCode: '',
    nickname: '',
    password: '',
    rePassword: '',
    checkCode: ''
})

const validatePass = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次输入密码'))
    } else if (value !== formData.password) {
        callback(new Error("两次输入密码不一致!"))
    } else {
        callback()
    }
}

const rules = {
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ],
    emailCode: [
        { required: true, message: '请输入邮箱验证码', trigger: 'blur' },
        { min: 5, max: 5, message: '验证码长度应为5位', trigger: 'blur' }
    ],
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 2, max: 10, message: '昵称长度应为2-10位', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 16, message: '密码长度应为6-16位', trigger: 'blur' }
    ],
    rePassword: [
        { validator: validatePass, trigger: 'blur' }
    ],
    checkCode: [
        { required: true, message: '请输入图片验证码', trigger: 'blur' },
        { min: 4, max: 4, message: '验证码长度应为4位', trigger: 'blur' }
    ]
}

const formRef = ref()
const loading = ref(false)
const checkCodeImg = ref('')
const emailCheckCode = ref('')
const dialogVisible = ref(false)
const sendEmailLoading = ref(false)
const cooldownTime = ref(0)
let timer = null

const getCheckCode = async () => {
    try {
        const res = await getCheckCodeService()
        checkCodeImg.value = res.data
    } catch (error) {
        ElMessage.error('获取图片验证码失败')
    }
}

const openEmailCodeDialog = () => {
    if (cooldownTime.value > 0) return
    if (!formData.email) {
        ElMessage.warning('请输入邮箱后再获取验证码')
        return
    }
    const emailRule = rules.email.find(rule => rule.type === 'email');
    if (emailRule && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
        ElMessage.warning('请输入正确的邮箱格式');
        return;
    }
    getCheckCode()
    dialogVisible.value = true
}

const sendEmailCode = async () => {
    if (!emailCheckCode.value) {
        ElMessage.warning('请输入图片验证码');
        return;
    }
    if (emailCheckCode.value.length !== 4) {
        ElMessage.warning('图片验证码长度为4位');
        return;
    }
    try {
        sendEmailLoading.value = true
        await sendEmailCodeService({ email: formData.email, checkCode: emailCheckCode.value })
        ElMessage.success('邮箱验证码发送成功，请注意查收')
        dialogVisible.value = false
        cooldownTime.value = 60
        timer = setInterval(() => {
            cooldownTime.value--
            if (cooldownTime.value <= 0) {
                clearInterval(timer)
            }
        }, 1000)
    } catch (error) {
        getCheckCode()
        emailCheckCode.value = ''
    } finally {
        sendEmailLoading.value = false
    }
}


const register = async () => {
    try {
        await formRef.value.validate()
        loading.value = true
        const params = {
            email: formData.email,
            code: formData.emailCode,
            nickName: formData.nickname,
            adminCode: formData.adminCode,
            password: formData.password
        }
        let data = await userRegisterService(params)
        ElMessage.success(data.msg ? data.msg : '注册成功')
        router.push('/login')
    } catch (error) {
        console.log('Validation or API error', error)
    } finally {
        loading.value = false
    }
}

const goToLogin = () => {
    router.push('/login')
}
</script>

<template>
    <div class="login-container">
        <div class="bg-effects"></div>

        <div class="login-box">
            <div class="brand">
                <div class="logo">云忆匣</div>
                <div class="subtitle">开启您的记忆之旅</div>
            </div>

            <el-form :model="formData" :rules="rules" ref="formRef" class="login-form" label-position="top">
                <el-form-item prop="email" label="邮箱">
                    <el-input v-model="formData.email" placeholder="请输入邮箱">
                        <template #prefix>
                            <el-icon>
                                <User />
                            </el-icon>
                        </template>
                    </el-input>
                <el-form-item prop="adminCode" label="管理员码" style="margin-top: 20px;">
                    <el-input v-model="formData.adminCode" placeholder="请输入管理员码（选填）">
                        <template #prefix>
                            <el-icon>
                                <Key />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>
                </el-form-item>

                <el-form-item prop="emailCode" label="邮箱验证码">
                    <div class="email-code-container">
                        <el-input v-model="formData.emailCode" placeholder="请输入邮箱验证码">
                            <template #prefix>
                                <el-icon>
                                    <Message />
                                </el-icon>
                            </template>
                        </el-input>
                        <el-button @click="openEmailCodeDialog" class="email-code-btn" :disabled="cooldownTime > 0">
                            {{ cooldownTime > 0 ? `${cooldownTime}s后重试` : '获取验证码' }}
                        </el-button>
                    </div>
                </el-form-item>

                <el-form-item prop="nickname" label="昵称">
                    <el-input v-model="formData.nickname" placeholder="请输入昵称">
                        <template #prefix>
                            <el-icon>
                                <User />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item prop="password" label="密码">
                    <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password>
                        <template #prefix>
                            <el-icon>
                                <Lock />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item prop="rePassword" label="确认密码">
                    <el-input v-model="formData.rePassword" type="password" placeholder="请再次输入密码" show-password>
                        <template #prefix>
                            <el-icon>
                                <Lock />
                            </el-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" class="login-button" @click="register" :loading="loading" round>
                        注册
                    </el-button>
                </el-form-item>

                <div class="register-link">
                    已有账号? <a href="javascript:void(0)" @click="goToLogin">立即登录</a>
                </div>
            </el-form>
        </div>

        <el-dialog v-model="dialogVisible" title="发送邮箱验证码" width="420px" center draggable :close-on-click-modal="false"
            class="email-dialog">
            <div class="dialog-content">
                <div class="email-display">
                    <span class="label">邮箱:</span>
                    <span class="value">{{ formData.email }}</span>
                </div>
                <div class="check-code-input-group">
                    <el-input v-model="emailCheckCode" placeholder="请输入图片验证码" @keyup.enter="sendEmailCode">
                        <template #prefix>
                            <el-icon>
                                <Key />
                            </el-icon>
                        </template>
                    </el-input>
                    <img :src="checkCodeImg" alt="验证码" class="check-code-img" @click="getCheckCode" title="点击刷新验证码" />
                </div>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="sendEmailCode" :loading="sendEmailLoading">
                        发送验证码
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<style lang="scss" scoped>
.login-container {
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    overflow: hidden;
    background: linear-gradient(135deg, #56ccf2 0%, #2f80ed 100%);

    .bg-effects {
        position: absolute;
        inset: -20vmax;
        pointer-events: none;

        &::before,
        &::after {
            content: '';
            position: absolute;
            width: 60vmax;
            height: 60vmax;
            border-radius: 50%;
            filter: blur(60px);
            mix-blend-mode: screen;
            opacity: 0.45;
            animation: float 18s ease-in-out infinite;
        }

        &::before {
            left: -10vmax;
            top: -8vmax;
            background: radial-gradient(closest-side, #a0c4ff, transparent 70%);
        }

        &::after {
            right: -8vmax;
            bottom: -6vmax;
            animation-delay: 3.5s;
            background: radial-gradient(closest-side, #ffd6a5, transparent 70%);
        }
    }
}

.login-box {
    width: 440px;
    padding: 36px 34px;
    border-radius: 18px;
    border: 1px solid rgba(255, 255, 255, 0.28);
    background: rgba(255, 255, 255, 0.16);
    backdrop-filter: blur(16px) saturate(140%);
    box-shadow:
        0 20px 40px rgba(31, 67, 116, 0.25),
        inset 0 1px 0 rgba(255, 255, 255, 0.35);
    transform: translateY(6px);
    animation: enter 600ms cubic-bezier(.2, .9, .2, 1) forwards;

    .brand {
        text-align: center;
        margin-bottom: 22px;

        .logo {
            font-size: 30px;
            font-weight: 800;
            letter-spacing: 2px;
            background: linear-gradient(90deg, #ffffff, #e9f3ff);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
            text-shadow: 0 1px 0 rgba(255, 255, 255, 0.25);
        }

        .subtitle {
            margin-top: 8px;
            font-size: 13px;
            color: rgba(255, 255, 255, 0.9);
            opacity: 0.9;
        }
    }

    .login-form {
        :deep(.el-form-item) {
            margin-bottom: 18px;
        }

        :deep(.el-form-item__label) {
            color: rgba(255, 255, 255, 0.95);
            font-weight: 600;
            letter-spacing: 0.2px;
        }

        :deep(.el-input__wrapper) {
            border-radius: 12px;
            padding: 4px 10px;
            background: rgba(255, 255, 255, 0.75);
            border: 1px solid rgba(255, 255, 255, 0.45);
            box-shadow:
                inset 0 1px 0 rgba(255, 255, 255, 0.6),
                0 1px 2px rgba(16, 24, 40, 0.06);
            transition: all .2s ease;
        }

        :deep(.el-input__wrapper:hover) {
            border-color: rgba(47, 128, 237, 0.7);
        }

        :deep(.el-input__wrapper.is-focus),
        :deep(.el-input__wrapper:focus-within) {
            border-color: #2f80ed;
            box-shadow:
                0 0 0 3px rgba(47, 128, 237, 0.15),
                inset 0 1px 0 rgba(255, 255, 255, 0.6);
            background: rgba(255, 255, 255, 0.9);
        }

        :deep(.el-input__prefix) {
            color: #2f80ed;
        }

        .email-code-container {
            display: flex;
            align-items: center;
            gap: 12px;
            width: 100%;

            .email-code-btn {
                height: 44px;
                padding: 0 20px;
                border-radius: 10px;
                border: 1px solid rgba(47, 128, 237, 0.5);
                background: rgba(47, 128, 237, 0.1);
                color: #2f80ed;
                font-weight: 600;
                transition: all .2s ease;
            }

            .email-code-btn:hover {
                background: rgba(47, 128, 237, 0.2);
                border-color: rgba(47, 128, 237, 0.7);
            }
        }

        .login-button {
            width: 100%;
            height: 46px;
            font-size: 16px;
            font-weight: 700;
            letter-spacing: 0.4px;
            border: 0;
            background: linear-gradient(135deg, #6ddcff 0%, #2f80ed 100%);
            box-shadow:
                0 10px 20px rgba(47, 128, 237, 0.35),
                inset 0 1px 0 rgba(255, 255, 255, 0.5);
            transition: transform .15s ease, box-shadow .15s ease, filter .2s ease;
        }

        .login-button:hover {
            transform: translateY(-1px);
            box-shadow:
                0 14px 26px rgba(47, 128, 237, 0.42),
                inset 0 1px 0 rgba(255, 255, 255, 0.55);
            filter: saturate(1.08);
        }

        .login-button:active {
            transform: translateY(0);
            box-shadow:
                0 8px 16px rgba(47, 128, 237, 0.28),
                inset 0 1px 0 rgba(255, 255, 255, 0.5);
        }

        .register-link {
            text-align: center;
            margin-top: 16px;
            font-size: 14px;
            color: rgba(255, 255, 255, 0.95);

            a {
                color: #ffffff;
                text-decoration: none;
                border-bottom: 1px dashed rgba(255, 255, 255, 0.7);
                padding-bottom: 1px;
                transition: opacity .2s ease;
            }

            a:hover {
                opacity: 0.9;
            }
        }
    }
}

@keyframes float {

    0%,
    100% {
        transform: translate(0, 0) scale(1);
    }

    50% {
        transform: translate(6vmin, -4vmin) scale(1.05);
    }
}

@keyframes enter {
    to {
        transform: translateY(0);
    }
}

/* 响应式 */
@media (max-width: 768px) {
    .login-box {
        width: 92% !important;
        padding: 26px 20px !important;
    }
}

:global(.email-dialog .el-dialog__body) {
    padding: 20px 30px;
}

.dialog-content {
    .email-display {
        margin-bottom: 18px;
        font-size: 15px;

        .label {
            color: #606266;
            font-weight: 600;
        }

        .value {
            margin-left: 8px;
            color: #303133;
        }
    }

    .check-code-input-group {
        display: flex;
        align-items: center;
        gap: 12px;

        .check-code-img {
            width: 110px;
            height: 42px;
            border-radius: 8px;
            border: 1px solid #dcdfe6;
            cursor: pointer;
            transition: opacity 0.2s;
        }

        .check-code-img:hover {
            opacity: 0.85;
        }
    }
}
</style>